//
//  LKAllScheduleViewController.m
//  YLHelper
//
//  Created by she1323 on 2018/5/2.
//  Copyright © 2018年 she1323. All rights reserved.
//

#import "LKAllScheduleViewController.h"
#import "LKSchedleDetailViewController.h"
#import "LKPopChoiceView.h"
#import "LKAddNewScheduleView.h"
#import "GFDatePicker.h"
#import "LKScheduleTypeCaluModel.h"
#import "LKScheduleListModel.h"
#import "UITextView+UITextView_LLKAdjust.h"
@interface LKAllScheduleViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)LKBaseTableview *tableview;
@property(nonatomic,strong)UIImage *bluepot;
@property(nonatomic,strong)UIView *bgView;
@property(nonatomic,strong)UIView *bgxView;
@property(nonatomic,strong)LKPopChoiceView *choiceView;
@property(nonatomic,strong)LKAddNewScheduleView *addScheduleView;
@property(nonatomic,copy)NSString *CalenderContent;
@property(nonatomic,copy)NSString *CalenderType;
@property(nonatomic,copy)NSString *CalenderName;
@property(nonatomic,copy)NSString *EntryTime;
@property(nonatomic,strong)NSMutableArray *allDataTypeArray;
@property(nonatomic,strong)NSMutableArray *datalistArray;
@property(nonatomic,assign)NSInteger PageIndex;
@property(nonatomic,assign)NSInteger MaxResultCount;

@end

@implementation LKAllScheduleViewController
-(LKBaseTableview *)tableview{
    if (!_tableview) {
        _tableview = [LKBaseTableview setTableviewWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT, WIDTH, HEIGHT - NAVIGATION_BAR_HEIGHT) style:UITableViewStylePlain registercellClasss:nil];
        [self.view addSubview:_tableview];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorStyle = UITableViewCellSelectionStyleGray;
        _tableview.tableFooterView = [[UIView alloc] init];
        _tableview.emptyDataSetSource = self;
        _tableview.emptyDataSetDelegate = self;
    }
    return _tableview;
}
/**
 头部下拉刷新
 */
-(void)headerReloadData{
    self.PageIndex = 1;
    self.MaxResultCount = 10;
    NSString *pageIndexStr = [NSString stringWithFormat:@"%ld",self.PageIndex];
    NSString *maxRsult = [NSString stringWithFormat:@"%ld",self.MaxResultCount];
    [self getAllScheduleDataWithPageIndex:pageIndexStr AndMaxCount:maxRsult];
}

/**
 尾部上拉加载更多
 */
-(void)footerReloadData{
    self.PageIndex++;
    
    NSString *pageIndexStr = [NSString stringWithFormat:@"%ld",self.PageIndex];
    NSString *maxRsult = [NSString stringWithFormat:@"%ld",self.MaxResultCount];
    [self getAllScheduleDataWithPageIndex:pageIndexStr AndMaxCount:maxRsult];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.CalenderType = @"10086";
    self.tableview.estimatedRowHeight = 200;
    self.PageIndex = 1;
    self.MaxResultCount = 10;
    NSString *pageIndexStr = [NSString stringWithFormat:@"%ld",self.PageIndex];
    NSString *maxRsult = [NSString stringWithFormat:@"%ld",self.MaxResultCount];
//    self.tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerReloadData)];
//    self.tableview.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerReloadData)];
    [self getCalendTypeData];
    [self getAllScheduleDataWithPageIndex:pageIndexStr AndMaxCount:maxRsult];
    // Do any additional setup after loading the view.
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [_bgView removeFromSuperview];
    [_bgxView removeFromSuperview];
    [_choiceView removeFromSuperview];
    [_addScheduleView removeFromSuperview];
}
-(void)setNavgationBackBtn{
    [super setNavgationBackBtn];
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:[UIImage imageNamed:@"jiahao"] forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    [btn addTarget:self action:@selector(addNewScheuldAction:) forControlEvents:UIControlEventTouchUpInside];
    WS(weakSelf)
    LKBaseButton *titleBtn = [LKBaseButton buttonWithFrame:CGRectMake(0, 0, 150, 40) type:UIButtonTypeCustom title:@"全部日程" titleColor:COLOR_HEX(0x000000) layercorne:0 font:[UIFont systemFontOfSize:17] backgroudColor:[UIColor whiteColor] AndActionBlock:^(UIButton *btn) {
        [weakSelf showChoiceView:btn];
    }];
    self.CalenderType = @"10086";
//    [titleBtn setImage:[UIImage imageNamed:@"zhankai"] forState:UIControlStateNormal];
    self.navigationItem.titleView = titleBtn;
//    CGFloat imgWidth = titleBtn.imageView.bounds.size.width;
//    CGFloat labWidth = titleBtn.titleLabel.bounds.size.width;
//    [titleBtn setImageEdgeInsets:UIEdgeInsetsMake(0, labWidth, 0, -labWidth)];
//    [titleBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -imgWidth, 0, imgWidth)];
}

/**
 添加新的日程信息

 @param btn 按钮
 */
-(void)addNewScheuldAction:(UIButton *)btn{
    if (!_bgxView) {
        _bgxView = [[UIView alloc] initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT, WIDTH, HEIGHT - NAVIGATION_BAR_HEIGHT)];
        _bgxView.alpha = 0.5f;
        _bgxView.backgroundColor = [UIColor blackColor];
    }
    if (!_addScheduleView) {
        WS(weakSelf)
        _addScheduleView = [[[NSBundle mainBundle] loadNibNamed:@"LKAddNewScheduleView" owner:self options:nil] lastObject];
        _addScheduleView.textView.placeholder = @"输入啦。。。";
        _addScheduleView.textView.layer.borderColor = blueDefault.CGColor;
        _addScheduleView.textView.layer.borderWidth = 1;
        [_addScheduleView.textView setAutoAdjust:YES];
        [[_addScheduleView.textView rac_textSignal] subscribeNext:^(NSString * _Nullable x) {
            weakSelf.CalenderContent = x;
        }];
        NSString *currentTimeStr = [NSString getCurrentTime];
        NSString *timeStr = [currentTimeStr componentsSeparatedByString:@" "][0];
        NSArray *timeArra = [timeStr componentsSeparatedByString:@"-"];
        _addScheduleView.dateShowLabel.text = [NSString stringWithFormat:@"%@年%@月%@日",timeArra[0],timeArra[1],timeArra[2]];
       NSString *timeS = [NSString stringWithFormat:@"%@-%@-%@",timeArra[0],timeArra[1],timeArra[2]];
        self.EntryTime = timeS;
        [[_addScheduleView.cancelBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            [weakSelf.bgxView removeFromSuperview];
            [weakSelf.addScheduleView removeFromSuperview];
        }];
        [_addScheduleView.sureBtn addTarget:self action:@selector(createNewScheadule) forControlEvents:UIControlEventTouchUpInside];
        UITapGestureRecognizer *datePicker = [[UITapGestureRecognizer alloc] init];
        [_addScheduleView.chooseBgView addGestureRecognizer:datePicker];
        [[datePicker rac_gestureSignal] subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
            [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
            [GFDatePicker showCustomDatePickerAtView:[UIApplication sharedApplication].keyWindow choosedDateBlock:^(NSDate *date) {
                NSString *dateStr = [NSString stringWithFormat:@"%@",date];
                NSString *timeStr = [dateStr componentsSeparatedByString:@" "][0];
                NSArray *timeArra = [timeStr componentsSeparatedByString:@"-"];
                weakSelf.addScheduleView.dateShowLabel.text = [NSString stringWithFormat:@"%@年%@月%@日",timeArra[0],timeArra[1],timeArra[2]];
                weakSelf.EntryTime = [NSString stringWithFormat:@"%@-%@-%@",timeArra[0],timeArra[1],timeArra[2]];
                
            } cancelBlock:^{
                
            }];
        }];
    }
//    [[UIApplication sharedApplication].keyWindow addSubview:_bgxView];
//    [[UIApplication sharedApplication].keyWindow addSubview:_addScheduleView];
    [self.view addSubview:_bgxView];
    [self.view addSubview:_addScheduleView];
    [self.view bringSubviewToFront:_addScheduleView];
    
    [_addScheduleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo([UIApplication sharedApplication].keyWindow);
        make.size.mas_equalTo(CGSizeMake(275 * WIDTH/375, 227 * HEIGHT/667));
    }];
}


-(void)showChoiceView:(UIButton *)btn{
    WS(weakSelf)
    if (!_bgView) {
        _bgView = [[UIView alloc] initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT, WIDTH, HEIGHT - NAVIGATION_BAR_HEIGHT)];
        _bgView.alpha = 0.5f;
        _bgView.backgroundColor = [UIColor blackColor];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removebackView:)];
        [_bgView addGestureRecognizer:tap];
    }
    if (!_choiceView) {
        _choiceView = [[LKPopChoiceView alloc] initWithFrame:CGRectMake(0, 0, WIDTH,self.allDataTypeArray.count * 50)];
        _choiceView.valueBlock = ^(NSString *title) {
            [btn setTitle:title forState:UIControlStateNormal];
            weakSelf.CalenderType = [NSString stringWithFormat:@"%ld",[weakSelf backTypeAccordingTitle:[[title componentsSeparatedByString:@"("] firstObject]]];
            [weakSelf.bgView removeFromSuperview];
            weakSelf.PageIndex = 1;
            weakSelf.MaxResultCount = 10;
            NSString *pageIndexStr = [NSString stringWithFormat:@"%ld",weakSelf.PageIndex];
            NSString *maxRsult = [NSString stringWithFormat:@"%ld",weakSelf.MaxResultCount];
            [weakSelf getAllScheduleDataWithPageIndex:pageIndexStr AndMaxCount:maxRsult];
        };
        _choiceView.titleArray = @[@"全部日程",@"客户生日",@"预到期订单",@"到期订单",@"自定义日程"];
        _choiceView.titleArray = self.allDataTypeArray;
        [[UIApplication sharedApplication].keyWindow addSubview:_choiceView];
        [UIView animateWithDuration:0.5 animations:^{
            _choiceView.frame = CGRectMake(0,NAVIGATION_BAR_HEIGHT,WIDTH ,_choiceView.titleArray.count * 50);
        }];
    }
    [[UIApplication sharedApplication].keyWindow addSubview:_bgView];
    [[UIApplication sharedApplication].keyWindow addSubview:_choiceView];
    [UIView animateWithDuration:0.5 animations:^{
        _choiceView.frame = CGRectMake(0,NAVIGATION_BAR_HEIGHT,WIDTH ,_choiceView.titleArray.count * 50);
    }];
}
-(void)removebackView:(UITapGestureRecognizer *)tap{
    [UIView animateWithDuration:0.5 animations:^{
        UIView *view = tap.view;
        [view removeFromSuperview];
        [_choiceView removeFromSuperview];
    }];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.datalistArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId = @"cellID";
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellId];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    LKScheduleListModel *model = self.datalistArray[indexPath.row];
    cell.textLabel.text = model.calenderName;
    cell.detailTextLabel.text = model.calenderContent;
    cell.textLabel.textColor = COLOR_HEX(0x565D66);
    cell.textLabel.font = [UIFont systemFontOfSize:16];
    cell.detailTextLabel.textColor = COLOR_HEX(0xA1A1A1);
    cell.detailTextLabel.font = [UIFont systemFontOfSize:13];
    cell.detailTextLabel.numberOfLines = 0;
    cell.imageView.image = self.bluepot;
//    if (!cell) {
//        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellId];
//        cell.selectionStyle = UITableViewCellSelectionStyleNone;
//        LKScheduleListModel *model = self.datalistArray[indexPath.row];
//        cell.textLabel.text = model.calenderName;
//        cell.detailTextLabel.text = model.calenderContent;
//        cell.textLabel.textColor = COLOR_HEX(0x565D66);
//        cell.textLabel.font = [UIFont systemFontOfSize:16];
//        cell.detailTextLabel.textColor = COLOR_HEX(0xA1A1A1);
//        cell.detailTextLabel.font = [UIFont systemFontOfSize:13];
//        cell.imageView.image = self.bluepot;
//    }
    
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewAutomaticDimension;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    LKSchedleDetailViewController *vc = [[LKSchedleDetailViewController alloc] init];
//    LKScheduleListModel *model = self.datalistArray[indexPath.row];
//    vc.shduleId = model.scheduleId;
//    [self.navigationController pushViewController:vc animated:YES];
}
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        LKScheduleListModel *model = self.datalistArray[indexPath.row];
        [self deleteScheduleInformationWithID:model];
    }
}

/**
 删除日程
 */
-(void)deleteScheduleInformationWithID:(LKScheduleListModel *)model{
    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:homeDeleteScheduleUrl parameters:@{@"Id":model.scheduleId} progress:^(NSProgress * _Nullable progress) {
        
    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        [self.datalistArray removeObject:model];
        [self.tableview reloadData];
    } failure:^(NSString * _Nullable errorMessage) {
        
    }];
}
-(UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView{
    return [UIImage imageNamed:@"zanwuricheng"];
}
#pragma mark 生成image
- (UIImage *)makeImageWithView:(UIView *)view withSize:(CGSize)size
{
    // 下面方法，第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了，关键就是第三个参数 [UIScreen mainScreen].scale。
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
    
}
-(UIImage *)bluepot{
    if (!_bluepot) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 5)];
        view.backgroundColor = COLOR_HEX(0x3677F7);
        view.layer.cornerRadius = 2.5;
        view.layer.masksToBounds = YES;
        _bluepot = [self makeImageWithView:view withSize:CGSizeMake(5, 5)];
    }
    return _bluepot;
}
/**
 创建添加新日程信息
 */
-(void)createNewScheadule{
    [self.bgxView removeFromSuperview];
    [self.addScheduleView removeFromSuperview];
    self.CalenderName = @"自定义日程";
    NSDictionary *param;
    if ([self.CalenderType integerValue] != 10086) {
        param = [NSDictionary dictionaryWithObjectsAndKeys:self.CalenderContent,@"CalenderContent",@"3",@"CalenderType",self.CalenderName,@"CalenderName",self.EntryTime,@"EntryTime", nil];
    }else{
        param = [NSDictionary dictionaryWithObjectsAndKeys:self.CalenderContent,@"CalenderContent",@"3",@"CalenderType",self.CalenderName,@"CalenderName",self.EntryTime,@"EntryTime", nil];
//        [SVProgressHUD showInfoWithStatus:@"请选择添加日程类型"];
//        return;
    }
    NSLog(@"参数%@",param);
    NSLog(@"请求头%@",[LKUserInforTool header]);
    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:homeAddScheduleUrl header:[LKUserInforTool header] parameters:param progress:^(NSProgress * _Nullable progress) {
        
    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        self.PageIndex = 1;
        self.MaxResultCount = 10;
        NSString *pageIndexStr = [NSString stringWithFormat:@"%ld",self.PageIndex];
        NSString *maxRsult = [NSString stringWithFormat:@"%ld",self.MaxResultCount];
        [self getAllScheduleDataWithPageIndex:pageIndexStr AndMaxCount:maxRsult];
        [[NSNotificationCenter defaultCenter] postNotificationName:tableviewReloadNotice object:nil];
        [self getCalendTypeData];
    } failure:^(NSString * _Nullable errorMessage) {
        
    }];

}

/**
 返回日程的类型

 @param title 头部字符串的值
 @return 类型
 */
-(NSInteger)backTypeAccordingTitle:(NSString *)title{
    if ([title isEqual:@"客户生日"]) {
        return 0;
    }else if ([title isEqual:@"预到期订单"]){
        return 1;
    }else if ([title isEqual:@"到期订单"]){
        return 2;
    }else if([title isEqual:@"自定义日程"]){
        return 3;
    }else{
        return 10086;
    }
    return 10086;
}
-(NSString *)backTitleStringAccordingType:(NSInteger)type{
    switch (type) {
        case 0:
            {
            return @"客户生日";
            }
            break;
        case 1:
        {
            return @"预到期订单";
        }
            break;
        case 2:
        {
            return @"到期订单";
        }
            break;
        case 3:
        {
            return @"自定义日程";
        }
            break;
        default:
            break;
    }
    return @"";
}

/**
 日程类型数组

 @return 数组
 */
-(NSMutableArray *)allDataTypeArray{
    if (!_allDataTypeArray) {
        _allDataTypeArray = [[NSMutableArray alloc] init];
        [_allDataTypeArray addObject:@"全部日程"];
    }
    return _allDataTypeArray;
}

/**
 列表数组

 @return 数组
 */
-(NSMutableArray *)datalistArray{
    if (!_datalistArray) {
        _datalistArray = [[NSMutableArray alloc] init];
    }
    return _datalistArray;
}
/**
 获取所有的日程类型信息
 */
-(void)getCalendTypeData{
//    self.timeDateStr
//    [self.allDataTypeArray removeAllObjects];
    for (NSInteger i = 0; i < self.allDataTypeArray.count; i++) {
        if (i == 0) {
            continue;
        }
        [self.allDataTypeArray removeObjectAtIndex:i];
    }
    if (self.timeDateStr == nil) {
        self.timeDateStr = [NSString getTimeStrAccoringDate:[NSDate date]];
    }
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:self.timeDateStr,@"IntradayDate", nil];
    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:homeScheduleTypeCalUrl header:[LKUserInforTool header] parameters:param progress:^(NSProgress * _Nullable progress) {
        
    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        NSArray *typeArra = responseObject[@"result"];
        NSLog(@"所有有%@",responseObject);
        for (NSDictionary *dict in typeArra) {
            LKScheduleTypeCaluModel *model = [LKScheduleTypeCaluModel modelWithDictionary:dict];
            NSString *title = [NSString stringWithFormat:@"%@(%@)",model.calenderName,model.calenderTypeSum];
            [self.allDataTypeArray addObject:title];
        }
        self.choiceView.titleArray = self.allDataTypeArray;
    } failure:^(NSString * _Nullable errorMessage) {
        
    }];
}

/**
 获取所有的日程列表信息
 */
-(void)getAllScheduleDataWithPageIndex:(NSString *)pageIndex AndMaxCount:(NSString *)maxCount{
    NSDictionary *param;
    if (!self.timeDateStr) {
        if ([self.CalenderType integerValue] != 10086) {
            param = @{@"PageIndex":pageIndex,@"MaxResultCount":maxCount,@"EntryTime":[[[NSString getCurrentTime] componentsSeparatedByString:@" "] firstObject],@"CalenderType":self.CalenderType};
        }else{
            param = @{@"PageIndex":pageIndex,@"MaxResultCount":maxCount,@"EntryTime":[[[NSString getCurrentTime] componentsSeparatedByString:@" "] firstObject]};
        }
    }else{
        if ([self.CalenderType integerValue] != 10086) {
            param = @{@"PageIndex":pageIndex,@"MaxResultCount":maxCount,@"EntryTime":self.timeDateStr};
        }else{
            param = @{@"PageIndex":pageIndex,@"MaxResultCount":maxCount,@"EntryTime":self.timeDateStr};
        }
    }

    
    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:homeAllScheduleUrl header:[LKUserInforTool header] parameters:param progress:^(NSProgress * _Nullable progress) {
        
    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        [self.tableview.mj_header endRefreshing];
        [self.tableview.mj_footer endRefreshing];
        if (self.PageIndex == 1) {
            [self.datalistArray removeAllObjects];
        }
//        if (!responseObject[@"result"][@"items"]) {
//
//        }else{
//
//        }
        NSArray *listArray = responseObject[@"result"] == NULL ? @[] : responseObject[@"result"];
//        NSString *count = responseObject[@"result"][@"totalCount"];
        for (NSDictionary *dic in listArray) {
            LKScheduleListModel *model = [LKScheduleListModel modelWithDictionary:dic];
            [self.datalistArray addObject:model];
        }
//        if ([count integerValue] == self.datalistArray.count) {
//            [self.tableview.mj_footer endRefreshingWithNoMoreData];
//        }
        if (self.datalistArray.count == 0) {
            self.tableview.mj_footer.hidden = YES;
        }
        [self.tableview reloadData];
        NSLog(@"lala%@",responseObject);
    } failure:^(NSString * _Nullable errorMessage) {

    }];
}
-(void)dealloc{
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
